//
//  FrindManage.m
//  QuanZiChat
//
//  Created by lanou3g on 15/11/25.
//  Copyright © 2015年 ZhongHongLin. All rights reserved.
//

#import "FrindManage.h"
#import "ContactManManager.h"
#import "TalkManage.h"
#import <AVOSCloudIM.h>
#import "ContactInfo.h"
#import "User.h"
#import "Friend.h"


@interface FrindManage()
//保存所有好友的数组
@property(nonatomic,strong)NSMutableArray *frindArray;

@end

@implementation FrindManage

static FrindManage *Manager = nil;
+(instancetype)defulManager{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        Manager = [[FrindManage alloc] init];
    });
    return Manager;
}

//懒加载frindArray
-(NSMutableArray *)frindArray{
    if (_frindArray == nil) {
        _frindArray = [[NSMutableArray alloc] init];
    }
    return _frindArray;
}


//添加好友(将好友信息以Array的形式加到_User表中的friend字段下)
-(void)addFriendWithUsername:(NSString *)username Handle:(void(^)())handle{
    //判断此人是否已经是好友(便利好友数组查找是否包含此UserName)
    for (ContactInfo *contact in self.frindArray) {
        if ([username isEqualToString:contact.name]) {
            NSLog(@"此人已是好友");
            return;
        }
    }
    //利用select语句得到username的全部信息(数组)
    [AVQuery doCloudQueryInBackgroundWithCQL:@"select * from _User where username = ?" pvalues:@[username] callback:^(AVCloudQueryResult *result, NSError *error) {
        //创建当前用户对象
        AVUser *user = [AVUser currentUser];
        //利用当前用户将username的全部信息存入friend字段下
        [user addObject:result.results[0] forKey:@"friends"];
        NSLog(@"添加成功");
        [user saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
            NSLog(@"%@",error);
            handle();
        }];
    }];
}


//从数据库中获得好友(_Uer表中和friends字段有关联的用户)
-(void)getFriendFromUserWithHandle:(void(^)())handle{
    //创建当前用户对象
    [self.frindArray removeAllObjects];
    AVUser *user = [AVUser currentUser];
    //得到当前用户对象的friend字段下的数组
    NSArray *Array = [user objectForKey:@"friends"];
    for (AVUser *user in Array) {
        //通过select语句进行查询
        [AVQuery doCloudQueryInBackgroundWithCQL:@"select * from _User where objectId = ?" pvalues:@[user.objectId] callback:^(AVCloudQueryResult *result, NSError *error) {
            //数组只有一个元素
            AVUser *user = result.results[0];
            //将好友信息加载到Model中
            ContactInfo *contact = [[ContactInfo alloc] init];
            contact.name = user.username;
            contact.UserID = user.objectId;
            //将user添加到数组中
            [self.frindArray addObject:contact];
            handle();
        }];
    }
}


//返回frindArray数组
-(NSMutableArray *)getBackFriend{
    return self.frindArray;
}


//从数据库中获取好友信息并添加到本地
-(void)StoreFriendMessageWithUser:(User *)user Handle:(void(^)())handle{
    //清空本地数据库
    [user removeUserfrineds:user.userfrineds];
    //从LeanCloud中获取用户自己的信息
    AVUser *myuser = [AVUser currentUser];
    //获取当前用户字段下的所有好友
    NSArray *Array = [myuser objectForKey:@"friends"];
    for (AVUser *friend1 in Array) {
        Friend *friend = [NSEntityDescription insertNewObjectForEntityForName:@"Friend" inManagedObjectContext:[TalkManage defulManage].managedObjectContext];
        [AVQuery doCloudQueryInBackgroundWithCQL:@"select * from _User where objectId = ?" pvalues:@[friend1.objectId] callback:^(AVCloudQueryResult *result, NSError *error) {
            //数组只有一个元素
            AVUser *user1 = result.results[0];
            //给好友信息赋值
            friend.friendID = user1.objectId;
            friend.friendname = user1.username;
            AVFile *file1 =  [[AVUser currentUser] objectForKey:@"headImage"];
            friend.friendpic = file1.url;
            // 给用户信息赋值
            user.username = myuser.username;
            [user addUserfrinedsObject:friend];
            //调用coraData方法保存数据
            [[TalkManage defulManage] saveContext];
            handle();
        }];
    }
}




@end
